package com.example.core.network.body

import okio.Buffer
import okio.ForwardingSink
import okio.Sink

/**
 * Created by zhudongao
 * Desc
 * Date 2020/12/6
 */
class CountingSink(
    delegateSink: Sink,
    private val uploadRequestBody: UploadProgressRequestBody
) :
    ForwardingSink(delegateSink) {

    var bytesWritten = 0L
    var contentLength = 0L
    var lastRefreshUiTime = 0L
    var progressCallback: ProgressResponseCallback? = uploadRequestBody.progressCallback

    override fun write(source: Buffer, byteCount: Long) {
        super.write(source, byteCount)
        if (contentLength <= 0) {
            contentLength = uploadRequestBody.contentLength()
        }
        bytesWritten += byteCount

        val curTime = System.currentTimeMillis()
        if (curTime - lastRefreshUiTime >= 100 || bytesWritten == contentLength) {
            progressCallback?.onResponseProgress(
                bytesWritten,
                contentLength,
                bytesWritten == contentLength
            )
            lastRefreshUiTime = System.currentTimeMillis()
        }
    }
}